package org.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Ajax {

	public static String post(String uri) throws IOException {

		URL url = null;
		
		url = new URL(uri);

		URLConnection conn = null;

		conn = url.openConnection();
	
		// 设置网络超时时间
		conn.setConnectTimeout(6000);

		InputStream is = null;

		is = conn.getInputStream();

		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		String str = null;

		StringBuffer sb = new StringBuffer();

		while ((str = br.readLine()) != null) {

			sb.append(str + "\n");
		}

		return sb.toString();
	}

	public static void main(String[] args) {
		
	}

	/**
	 * 下载文件到本地
	 * 
	 * @param urlString
	 * @param filename
	 * @param savePath
	 * @throws Exception
	 */
	public static void download(String urlString, String filename, String savePath) throws Exception {
		// 构造URL
		URL url = new URL(urlString);
		// 打开连接
		URLConnection con = url.openConnection();
		// 设置请求超时为5s
		con.setConnectTimeout(5 * 1000);
		// 输入流
		InputStream is = con.getInputStream();

		// 1K的数据缓冲
		byte[] bs = new byte[1024];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		File sf = new File(savePath);
		if (!sf.exists()) {
			sf.mkdirs();
		}
		OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
	}

	/**
	 * 验证url是否正确
	 * 
	 * @param uri
	 * @return boolean
	 */
	public static boolean Verification(String uri) {

		boolean result = true;

		URL url = null;
		try {
			url = new URL(uri);
		} catch (MalformedURLException e) {
			result = false;
		}

		URLConnection conn = null;
		try {
			conn = url.openConnection();
		} catch (IOException e) {
			result = false;
		}

		InputStream is = null;
		try {
			is = conn.getInputStream();
		} catch (IOException e) {
			result = false;
		}

		return result;
	}
}
